import path from 'path';
import fs from 'fs';
import _ from 'lodash';
import { Request, Response, NextFunction } from 'express';
import { getVideos, addVideos, getVideosById, countFavorites, favoriteCount, findFileById, deleteFileById, createFile, updateVideos, getVideoById, byKeyWordSelect, statusChange, deleteVideo } from './videos.service';
import { IMAGE_TYPE_VIDEO } from "../app/constants";
import { createFavorites, deleteFavorites, getFavorite } from '../favorites/favorites.service';
import { VideoModel } from './videos.model';


/**
 * 获取
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let pageNo = request.query.pageNo;
  let pageSize = request.query.pageSize;
  let status = request.query.status;
  let user = request.user;
  let userId = 0
  
  if (user && user.id > 0) {
    userId = user.id;
  }

  try {
    // const data = await getVideos(-1, 5, parseInt(`${pageNo}`, 10));
    const data = await getVideos(-1, parseInt(`${pageSize}`), parseInt(`${pageNo}`, 10), parseInt(`${status}`, 10));
    
    if(userId > 0){
      for (const item of data.data as any) {
        let favoriteParam = { user_id: user.id, type: IMAGE_TYPE_VIDEO, target_id: item.id }
        let favorite = await getFavorite(favoriteParam);
        item.isLike = (favorite as any).length > 0
      }
    }
    response.send(data);
  } catch (error) {
    next(error)
  }
};

/**
 * 按 user ID 获取
 */
export const byIdIndex = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取用户 ID
  const userId = request.query.userId;
  const pageNo = request.query.pageNo;

  try {
    const data = await getVideosById(parseInt(`${userId}`, 10), 9, parseInt(`${pageNo}`, 10));
    const favorite_count = await favoriteCount(parseInt(`${userId}`, 10));
    
    if ((userId as any) > 0) {
      for (const item of data.data as any) {        
        let favoriteParam = { user_id: parseInt(`${userId}`, 10), type: IMAGE_TYPE_VIDEO, target_id: item.id }
        let favorite = await getFavorite(favoriteParam);
        item.isLike = (favorite as any).length > 0
      }
    }
    
    (data as any).favorite_count = favorite_count;
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 获取内容(按 ID 查找)
 */
export const videoById = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getVideoById(parseInt(postId, 10));

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 按关键词搜索（模糊查询）
 */
export const selectByKey = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取关键词
  let { keyWord } = request.query;

  try {
    const data = await byKeyWordSelect(keyWord);
    response.send(data);
  } catch (error) {
    next(error)
  }
}

/**
 * 创建
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取
  const videosModel = request.body;

  try {
    if (videosModel.id && videosModel.id > 0) {
      let image_id = videosModel.image_id
      let img = await findFileById(image_id, 0, 0);
      if (!img || img.length === 0) {
        let imgs = await findFileById(0, videosModel.id, 23);
        if (imgs && imgs.length > 0) {
          videosModel.image_id = imgs[imgs.length - 1].id
        }
      }
      const data = await updateVideos(videosModel, parseInt(videosModel.id, 10));
      response.send(data);
    } else {
      const data = await addVideos(videosModel);
      response.send(data);
    }
  } catch (error) {
    next(error);
  }
};

/**
 * 点赞收藏
 */
export const setFavorite = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取用户 ID
  const userId = request.user.id;

  // 视频 ID
  const { videoId } = request.body;

  // 建议按视频 ID 是否存在 （数据库查询）

  // 检查收藏
  let record = await getFavorite({ user_id: userId, target_id: videoId, type: IMAGE_TYPE_VIDEO});

  // 检查已收藏删除收藏
  if (record && (record as any).length >0) {
    await deleteFavorites((record[0] as VideoModel).id);
    await countFavorites(-1, videoId);
    response.send({ msg: '取消收藏' })
    return;
  };

  // 添加收藏
  const setFavorite = await createFavorites({ user_id: userId, target_id: videoId, type: IMAGE_TYPE_VIDEO });

  // 增加点赞数量
  await countFavorites(1, videoId);

  response.send(setFavorite);
};

/**
 * 上传文件
 */
export const uploads = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取类型
  let { target_type, target_id } = request.body;
  if (target_id === undefined) {
    target_type = request.query.target_type;
    target_id = request.query.target_id;
  }

  // 文件信息
  const fileInfo = _.pick(request.file, [
    'id',
    'target_id',
    'target_type',
    'url',
    'originalname',
    'mimetype',
    'filename',
    'size'
  ])

  fileInfo['url'] = "/videoCover/";
  fileInfo['target_type'] = parseInt(`${target_type}`, 10);
  fileInfo['target_id'] = parseInt(`${target_id}`, 10);

  try {
    // 保存文件信息
    const data = await createFile({
      ...fileInfo,
      ...request.fileMataData,
      //target_type: parseInt(`${target_type}`, 10), // target_type: `${target_type}` // target_type: target_type as string  转换字符串两种写法
    })

    let post = {
      id: parseInt(`${target_id}`, 10),
      image_id: (data as any).insertId,
    }

    const videoData = await updateVideos(post as any, parseInt(`${target_id}`, 10));

    // 做出响应
    response.status(200).send(videoData)
  } catch (error) {
    next(error);
  }
}

/**
 * 文件服务
 */
export const serve = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 从地址参数里得到文件 ID
  const { fileId } = request.params;

  try {
    // 查找文件信息
    const file = await findFileById(parseInt(fileId, 10), 0, 0);

    // 要提供的图像尺寸
    const { size } = request.query;

    // 文件名与目录
    let filename = file[0].filename;
    let root = 'uploads/videoCover/resized';
    let resized = 'resized';

    if (size) {
      // 可用的图像尺寸
      const imageSize = ['lerge', 'medium', 'thumbnail'];

      // 检查文件尺寸是否可用
      if (!imageSize.some(item => item == size)) {
        throw new Error('FILE_NOT_FOUND');
      }

      // 检查文件是否存在
      const fileExist = fs.existsSync(
        path.join(root, resized, `${filename}-${size}`),
      )

      // 设备文件名与目录
      if (fileExist) {
        filename = `${filename}-${size}`;
        root = path.join(root, resized);
      }
    }

    // 做出响应
    response.sendFile(filename, {
      root,
      headers: {
        'Content-Type': file[0].mimetype
      }
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 获取文件名
 */
export const getFileName = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取文件 ID
  const { fileId } = request.body;
  let file = await findFileById(fileId, 0, 0)
  if (!file || file.length <= 0) {
    response.send({
      status: 2,
      msg: 'not found'
    })
    return;
  }
  let result = await deleteFileById(file[0])

  response.send({
    status: 1,
    msg: 'ok'
  })

}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.params;

  // 删除内容
  try {
    const data = await deleteVideo(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 状态
 */
export const status = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  const postId = request.body.id;

  // 获取内容
  const post = _.pick(request.body, ['status']);

  // 执行
  try {
    const data = await statusChange(parseInt(postId, 10), post);
    
    response.send(data);
  } catch (error) {
    next(error);
  }
};
